﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GestorDeFlotasDesktop.AbmRol
{
    public partial class AbmRol : Form
    {
        private Modelo.FormActions.Actions action = Modelo.FormActions.Actions.Alta;
        private int selected_elem = -1;

        public AbmRol(Modelo.FormActions.Actions runAction, int id)
        {
            InitializeComponent();
            switch (runAction)
            {
                case Modelo.FormActions.Actions.Baja:
                    selected_elem = id;
                    this.loadData(selected_elem);
                    action = Modelo.FormActions.Actions.Baja;
                    func.Enabled = false;
                    this.aceptar_btn.Text = "Eliminar";
                    this.tb_rol.Enabled = false;
                    cb_hab.Enabled = false;
                    break;
                case Modelo.FormActions.Actions.Modificacion:
                    selected_elem = id;
                    this.loadData(selected_elem);
                    action = Modelo.FormActions.Actions.Modificacion;
                    aceptar_btn.Text = "Modificar";
                    cb_hab.Enabled = true;
                    tb_rol.Enabled = true;
                    break;
            }
            
        }

        public AbmRol(Modelo.FormActions.Actions runAction)
        {
            InitializeComponent();
            cb_hab.Enabled = false;
        }

        private void loadData(int id)
        {
            using (SqlConnection con = Modelo.Modelo.createConnection())
            {
                SqlDataAdapter da = new SqlDataAdapter(Modelo.SqlQueries.getRoleById(selected_elem), con);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataRow rol_info = dt.Rows[0];
                tb_rol.Text = rol_info.ItemArray[1].ToString();
                cb_hab.Checked = (bool)rol_info.ItemArray[2];

                SqlDataAdapter rol_perm_da = new SqlDataAdapter(Modelo.SqlQueries.getRolePermissions(selected_elem), con);
                DataTable rol_perm_dt = new DataTable();
                rol_perm_da.Fill(rol_perm_dt);
                foreach (DataRow perm in rol_perm_dt.Rows)
                {
                    Convert.ToInt32(perm.ItemArray[0].ToString());
                    string key = String.Empty;
                    foreach (KeyValuePair<string, int> pair in Modelo.Permissions.PermissionsDict)
                    {
                        if (pair.Value == Convert.ToInt32(perm.ItemArray[0].ToString()))
                        {
                            key = pair.Key;
                            break;
                        }
                    }
                    foreach (Control c in func.Controls)
                    {
                        if (c is CheckBox)
                        {
                            if (((CheckBox)c).Text.Equals(key))
                            {
                                ((CheckBox)c).Checked = true;
                            }
                        }
                    }
                    

                }

            }
        }

        private void aceptar_btn_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(tb_rol.Text))
            {
                switch (action)
                {

                    case Modelo.FormActions.Actions.Alta:
                        {
                            using (SqlConnection con = Modelo.Modelo.createConnection())
                            {
                                try
                                {
                                    Modelo.Modelo.openConnection(con);
                                    SqlCommand comando_add_user = new SqlCommand(Modelo.SqlQueries.addRole(tb_rol.Text), con);
                                    comando_add_user.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
                            using (SqlConnection con2 = Modelo.Modelo.createConnection())
                            {
                                try
                                {
                                    Modelo.Modelo.openConnection(con2);
                                    SqlCommand comando_get_role_id = new SqlCommand(Modelo.SqlQueries.getRoleIdByName(tb_rol.Text), con2);
                                    SqlDataReader reader = comando_get_role_id.ExecuteReader();
                                    List<int> permissions = new List<int>();
                                    while (reader.Read())
                                    {
                                        foreach (Control c in func.Controls)
                                        {
                                            if (c is CheckBox)
                                            {
                                                if (((CheckBox)c).Checked)
                                                {
                                                    permissions.Add(Modelo.Permissions.PermissionsDict[c.Text]);
                                                }
                                            }
                                        }
                                        SqlConnection con3 = Modelo.Modelo.createConnection();
                                        Modelo.Modelo.openConnection(con3);
                                        SqlCommand comando_add_role_permissions = new SqlCommand(Modelo.SqlQueries.addRolePermissions(Convert.ToInt32(reader.GetDecimal(0)), permissions), con3);
                                        comando_add_role_permissions.ExecuteNonQuery();
                                        Modelo.Modelo.closeConnection(con3);
                                    }

                                    MessageBox.Show(String.Format("Rol {0} agregado", tb_rol.Text));
                                    Login.Login.mainForm.openForm(new AbmRol(Modelo.FormActions.Actions.Alta));
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
                        }
                        break;
                    case Modelo.FormActions.Actions.Baja:
                        using (SqlConnection con = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                SqlCommand comando = new SqlCommand(Modelo.SqlQueries.deleteRole(selected_elem), con);
                                Modelo.Modelo.openConnection(con);
                                comando.ExecuteNonQuery();
                                MessageBox.Show(String.Format("Rol {0} eliminado", tb_rol.Text));
                                Login.Login.mainForm.openForm(new AbmRol(Modelo.FormActions.Actions.Alta));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                Modelo.Modelo.closeConnection(con);
                            }
                        }
                        break;
                    case Modelo.FormActions.Actions.Modificacion:
                        List<int> permissions_list = new List<int>();
                        foreach (Control c in func.Controls)
                        {
                            if (c is CheckBox)
                            {
                                if (((CheckBox)c).Checked)
                                {
                                    permissions_list.Add(Modelo.Permissions.PermissionsDict[c.Text]);
                                }
                            }
                        }

                        using (SqlConnection connection = Modelo.Modelo.createConnection())
                        {
                            try
                            {
                                Modelo.Modelo.openConnection(connection);
                                SqlCommand comando = new SqlCommand(Modelo.SqlQueries.updateRole(selected_elem, tb_rol.Text, permissions_list, cb_hab.Checked), connection);
                                comando.ExecuteNonQuery();
                                MessageBox.Show(String.Format("Rol {0} modificado", tb_rol.Text));
                                Login.Login.mainForm.openForm(new AbmRol(Modelo.FormActions.Actions.Alta));
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        break;
                }
            }
            else
            {
                MessageBox.Show("ERROR: El nombre del rol es obligatorio.");
            }
        }

        private void AbmRol_Load(object sender, EventArgs e)
        {

        }

    }
}
